import { observable, action } from 'mobx';
// 接口
import * as loginApi from '~/apis/login/loginApi';
import * as dashboardApi from '~/apis/dashboard/dashboardApi';

interface UserLogin {
  username: string
  password: string
  rememberMe: boolean
}

type LocaleType = (
  | 'enUS'
  | 'zhCN'
);

const state = observable({
  loading: false,
  locale: 'enUS',
  currentInfo: {} as any,
  showAlert: false,
});

// 登录
const login = action(async (params: UserLogin) => loginApi.login(params));

// 登出
const logout = action(async () => loginApi.logout().finally(() => {
  state.currentInfo = {};
}));

// 获取当前用户信息
const getCurrentInfo = action(async () => dashboardApi.getCurrentInfo().then((res) => {
  state.currentInfo = res.data;
}));

// 检测是否有未读的系统消息
const checkMessageAlert = action(async () => dashboardApi.checkMsg().then((res) => {
  state.showAlert = res.data;
}));

// 全局设定语言
const updateLocal = action((locale: LocaleType) => {
  state.locale = locale;
});

export const userService = {
  state,
  login,
  logout,
  updateLocal,
  getCurrentInfo,
  checkMessageAlert,
};
